<script setup>
import { ref, onMounted, computed } from 'vue';
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from 'element-plus';
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();
const loading = ref(false);
const riderInfo = ref({});
const pendingOrders = ref([]); // 待分配的订单

// 获取骑手信息
const getRiderInfo = async () => {
  try {
    if (userStore.userId) {
      const { data: res } = await request.get(`/rider/user/${userStore.userId}`);
      if (res) {
        riderInfo.value = res;
      }
    }
  } catch (error) {
    console.error('获取骑手信息失败', error);
    ElMessage.error('获取骑手信息失败');
  }
};

// 获取待分配订单
const getPendingOrders = async () => {
  loading.value = true;
  try {
    // 获取未分配的订单
    const { data: res } = await request.get('/rider/deliveries/status', {
      params: {
        status: 'PENDING' // 获取待分配状态的订单
      }
    });
    if (res) {
      console.log('获取到的订单:', res); // 添加日志查看返回数据
      pendingOrders.value = res;
    }
  } catch (error) {
    console.error('获取待分配订单失败', error);
    ElMessage.error('获取待分配订单失败');
  } finally {
    loading.value = false;
  }
};

// 领取订单
const handleClaimOrder = async (delivery) => {
  try {
    await ElMessageBox.confirm(`确认领取订单 ${delivery.orderNo || delivery.id} 吗？`, '领取订单', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    });
    
    await request.put('/rider/claim', {
      deliveryId: delivery.id,
      riderId: riderInfo.value.id
    });
    
    ElMessage.success('领取订单成功');
    await getPendingOrders();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('领取订单失败', error);
      ElMessage.error(typeof error === 'string' ? error : '领取订单失败');
    }
  }
};

// 格式化状态
const formatStatus = (status) => {
  const statusMap = {
    'PENDING': '等待分配',
    'ASSIGNED': '待取件',
    'PICKED': '配送中',
    'DELIVERED': '已送达',
    // 添加订单状态的映射
    'PENDING_PAYMENT': '待付款',
    'PAID': '已付款',
    'SHIPPED': '已发货',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  };
  return statusMap[status] || status;
};

// 格式化支付方式
const formatPaymentType = (type) => {
  const paymentMap = {
    'ONLINE': '在线支付',
    'CASH': '货到付款'
  };
  return paymentMap[type] || type;
};

// 获取标签类型
const getTagType = (status) => {
  const typeMap = {
    'DELIVERED': 'success',
    'PICKED': 'warning',
    'ASSIGNED': 'info',
    'PENDING': 'info',
    // 添加订单状态的标签类型
    'PENDING_PAYMENT': 'info',
    'PAID': 'warning',
    'SHIPPED': 'warning',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  };
  return typeMap[status] || 'info';
};

// 获取支付方式标签类型
const getPaymentTagType = (type) => {
  return type === 'CASH' ? 'danger' : 'success';
};

onMounted(async () => {
  await getRiderInfo();
  await getPendingOrders();
});
</script>

<template>
  <div class="orders-list">
    <!-- 待分配订单 -->
    <el-card class="list-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span class="title">订单大厅</span>
          <el-button type="primary" @click="getPendingOrders">刷新</el-button>
        </div>
      </template>
      
      <div v-if="pendingOrders.length === 0" class="empty-list">
        <el-empty description="暂无待分配订单"></el-empty>
      </div>
      
      <div v-else class="orders-grid">
        <el-card 
          v-for="order in pendingOrders" 
          :key="order.id"
          shadow="hover" 
          class="order-card"
        >
          <div class="order-header">
            <div class="order-title">
              <span class="order-no">订单号: {{ order.orderNo || '未知' }}</span>
              <span class="order-amount">¥{{ order.totalAmount || '0.00' }}</span>
            </div>
            <div class="order-status-row">
              <div class="status-group">
                <div class="status-label">配送状态:</div>
                <el-tag :type="getTagType(order.deliveryStatus)" size="small" class="status-tag">
                  {{ formatStatus(order.deliveryStatus) }}
                </el-tag>
              </div>
              
              <div class="status-group">
                <div class="status-label">订单状态:</div>
                <el-tag :type="getTagType(order.orderStatus)" size="small" effect="plain" class="status-tag">
                  {{ formatStatus(order.orderStatus) }}
                </el-tag>
              </div>
              
              <div v-if="order.paymentType" class="status-group">
                <div class="status-label">支付方式:</div>
                <el-tag 
                  :type="getPaymentTagType(order.paymentType)" 
                  size="small"
                  class="status-tag"
                >
                  {{ formatPaymentType(order.paymentType) }}
                </el-tag>
              </div>
            </div>
          </div>
          
          <div class="divider"></div>
          
          <div class="order-info">
            <div class="info-item">
              <i class="el-icon-time"></i>
              <span class="info-label">创建时间:</span>
              <span>{{ new Date(order.createTime).toLocaleString() }}</span>
            </div>
            
            <div class="info-item">
              <i class="el-icon-location"></i>
              <span class="info-label">送达地址:</span>
              <span>{{ order.deliveryAddress || '无地址信息' }}</span>
            </div>
            
            <div class="detailed-address" v-if="order.addressInfo?.detailedAddress && order.addressInfo.detailedAddress !== order.deliveryAddress">
              <span class="text-small text-gray">详细地址: {{ order.addressInfo.detailedAddress }}</span>
            </div>
            
            <div v-if="order.paymentType === 'CASH'" class="payment-notice">
              <el-alert
                title="此订单为货到付款，请配送时向客户收取货款"
                type="warning"
                :closable="false"
                show-icon
              />
            </div>
          </div>
          
          <div class="divider"></div>
          
          <div class="order-actions">
            <el-button 
              type="primary" 
              size="default" 
              @click="handleClaimOrder(order)"
              :disabled="riderInfo.status !== 'AVAILABLE'"
            >
              领取订单
            </el-button>
          </div>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.orders-list {
  padding: 20px;
}

.list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.empty-list {
  padding: 40px 0;
}

.orders-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.order-card {
  transition: all 0.3s;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  padding-bottom: 60px; /* 为固定按钮腾出空间 */
}

.order-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
}

.order-header {
  margin-bottom: 15px;
}

.order-title {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.order-no {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.order-amount {
  font-size: 16px;
  color: #f56c6c;
  font-weight: bold;
}

.order-status-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.status-group {
  display: flex;
  align-items: center;
}

.status-label {
  font-size: 13px;
  color: #909399;
  margin-right: 5px;
}

.status-tag {
  margin-right: 2px;
}

.divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 15px 0;
}

.order-info {
  margin-bottom: 10px;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
  align-items: flex-start;
}

.info-label {
  color: #606266;
  margin-right: 8px;
  min-width: 70px;
  font-size: 14px;
}

.detailed-address {
  margin-top: 5px;
  margin-left: 78px;
  margin-bottom: 10px;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  position: absolute;
  bottom: 0;
  right: 0;
  width: 100%;
  padding: 15px 20px;
  background-color: #f9f9f9;
  border-top: 1px solid #ebeef5;
}

.text-gray {
  color: #909399;
  font-style: italic;
}

.text-small {
  font-size: 12px;
}

.payment-notice {
  margin: 15px 0;
}
</style>